package com.nwpu.am.shiro;

import com.nwpu.am.constant.RoleConstant;
import com.nwpu.am.constant.properties.ShiroProperties;
import com.nwpu.am.pojo.entity.Permission;
import com.nwpu.am.pojo.entity.User;
import com.nwpu.am.service.PermissionService;
import com.nwpu.am.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

/**
 * MyRealm
 *
 * @author Roy
 * @version 1.0
 * {@code @date} 2024/6/5
 */

@Component
@Slf4j
public class MyRealm extends AuthorizingRealm {
    @Resource
    private UserService userService;
    @Resource
    private PermissionService permissionService;
    @Resource
    private ShiroProperties shiroProperties;

    // 登录认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {
        log.info("Shiro认证。。。");
        // 从token中获取登录信息
        String username = authenticationToken.getPrincipal().toString();
        // 根据用户名查询数据库
        User user = userService.findByUsername(username);
        log.info("查询结果：{}", user);
        if (user != null) {
            // 验证密码，SimpleAuthenticationInfo自动实现，提供principals、credentials、盐值、当前Realm的名字
            /*
             * 在shiro中，用户需要提供principals （身份）和credentials（证明）给shiro，从而应用能验证用户身份.
             * principals:身份即主体的标识属性,可以是任何东西.如用户名,邮箱等.唯一即可.一个主体可以有多个principals，但只有一个Primary principals，一般是用户名/密码/手机号。
             * credentials:证明/凭证，即只有主体知道的安全值。如密码
             * 最常见的principals和credentials组合就是用户名、密码了。
             */
            ByteSource salt = ByteSource.Util.bytes(shiroProperties.getSalt());
            log.info("认证盐：{}", shiroProperties.getSalt());
            return new SimpleAuthenticationInfo(username, user.getPassword(), salt, this.getName());
        }
        throw new AuthenticationException("用户不存在");
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        log.info("Shiro授权。。。");
        // 获取用户
        String username = (String) principalCollection.getPrimaryPrincipal();
        // 根据用户名查询数据库，得到用户权限信息
        User user = userService.findByUsername(username);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addRole(RoleConstant.getRole(user.getRole()));
        List<Permission> permissions = permissionService.findByUsername(username);
        log.info("用户权限：{}", permissions);
        // 用户授权
        List<String> permissionList = permissions.stream()
                .map(Permission::getPermissionName)
                .collect(Collectors.toList());
        if (!permissionList.isEmpty()) {
            info.addStringPermissions(permissionList);
        }
        return info;
    }
}
